﻿using System;
using System.Drawing;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using Sumen.Business;
using DevExpress.XtraEditors;
using Sumen.Business.Presenter.Actor;
using Sumen.Business.Presenter.Sys;
using Sumen.Library.Classes.Common;
using Sumen.Library.Classes.Connection;
using Sumen.Library.Enum;
using Sumen.Model.Model;

namespace Sumen.GUI.Entities
{
    public partial class Frm_Employee_Edit : XtraForm
    {


        #region Property
        DateTime _defaultBirthday = new DateTime(1980, 1, 1);
        DateTime _defaultToday = DateTime.Now;
        private EmployeePresenter _employeePresenter;
        private SysRolePresenter _sysRolePresenter;
        private EnumFormCode _fromCode = EnumFormCode.FrmEmployee;
        private EnumFormStatus _enumFormStatus;
        private employee _emp;
        private string _fileImageUrl;
        string _urlSave = ClsConnection.LocationSave;
        public employee Emp
        {
            get { return _emp; }
            set { _emp = value; }
        }
        public EnumFormStatus EnumFormStatus
        {
            get { return _enumFormStatus; }
            set
            {
                _enumFormStatus = value;
                if (_enumFormStatus == EnumFormStatus.Add)
                {
                    buttonsArray1.btnSua.Enabled = false;
                    buttonsArray1.btnThem.Enabled = true;
                }
                else if (_enumFormStatus == EnumFormStatus.Modify)
                {
                    buttonsArray1.btnSua.Enabled = true;
                    buttonsArray1.btnThem.Enabled = false;
                }
            }
        }
        #endregion

        /// <summary>
        /// ///////////////////////////////////////////////////////////////////////////////////////////////////////
        /// </summary>

        #region Form

        public Frm_Employee_Edit()
        {
            InitializeComponent();
            _employeePresenter = new EmployeePresenter();
            _urlSave = Path.Combine(_urlSave, "NhanVien");
        }

        private void Frm_Employee_Edit_Load(object sender, EventArgs e)
        {
            LoadForm();
        }

        #endregion

        /// <summary>
        /// ///////////////////////////////////////////////////////////////////////////////////////////////////////
        /// </summary>


        #region Button event

        private void buttonsArray1_btnEventAdd_click(object sender, EventArgs e)
        {
            if (Validation())
            {
                if (_enumFormStatus == EnumFormStatus.Add)
                {
                    //add
                    employee newEmployee = addEmp();
                    if (_employeePresenter.Add(newEmployee) > 0)
                    {
                        ClsMsgBox.ThongTin("Thêm mới nhân viên thành công");
                        ClsPublic.WriteLog(_fromCode, EnumFormStatus.Modify, newEmployee.Emp_FullName, "");
                        _emp = newEmployee;
                        if (!string.IsNullOrEmpty(_fileImageUrl))
                        {
                            newEmployee.Emp_Avatar = InitAvatarFileName(_emp.Emp_Username);
                            copyImage();
                            _employeePresenter.Update(newEmployee, newEmployee.Emp_Username);
                        }
                        this.EnumFormStatus = EnumFormStatus.Modify;
                    }
                }
            }
        }

        private void buttonsArray1_btnEventUpdate_click(object sender, EventArgs e)
        {
            if (Validation())
            {
                if (_enumFormStatus == EnumFormStatus.Modify)
                {
                    employee newEmployee = addEmp();
                    newEmployee.Emp_Username = _emp.Emp_Username;
                    if (!string.IsNullOrEmpty(_fileImageUrl))
                    {
                        newEmployee.Emp_Avatar = InitAvatarFileName(_emp.Emp_Username);
                        copyImage();
                    }
                    if (_employeePresenter.Update(newEmployee, newEmployee.Emp_Username) > 0)
                    {

                        ClsMsgBox.ThongTin("Cập nhật nhân viên thành công");
                        ClsPublic.WriteLog(_fromCode, EnumFormStatus.Modify, newEmployee.Emp_FullName, "");
                    }

                }
            }
        }

        private void buttonsArray1_btnEventClose_click(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void btnImage_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                _fileImageUrl = openFileDialog1.FileName;
                try
                {
                    FileStream fs = new FileStream(_fileImageUrl, FileMode.Open);
                    Image img = Image.FromStream(fs);
                    pictureEdit1.Image = img;
                    fs.Close();

                }
                catch
                {

                }
            }
        }

        #endregion


        /// <summary>
        /// ///////////////////////////////////////////////////////////////////////////////////////////////////////
        /// </summary>



        #region MEthod

        void LoadForm()
        {
            if (_enumFormStatus == EnumFormStatus.Add)
            {
                txtFullName.EditValue = null;
                txtPhone.EditValue = null;
                txtAddress.EditValue = null;
                txtContact.EditValue = null;
                txtEmail.EditValue = null;


                txtDistrict.EditValue = null;
                txtCity.EditValue = null;

                txtCMND.EditValue = null;
                txtMaSoThue.EditValue = null;
                txtBirthday.DateTime = _defaultBirthday;
                chkGender.Checked = false;
                txtNgayTuyen.DateTime = _defaultToday;
                txtSucKhoe.EditValue = null;
                //newEmployee.Emp_Avatar = txtFullName.EditValue + string.Empty;
                pictureEdit1.Image = null;



                chkActived.CheckState = CheckState.Checked;
            }
            else if (_enumFormStatus == EnumFormStatus.Modify)
            {
                txtFullName.EditValue = _emp.Emp_FullName;
                txtPhone.EditValue = _emp.Emp_Phone;
                txtAddress.EditValue = _emp.Emp_Address;
                txtContact.EditValue = _emp.Emp_Contact;
                txtEmail.EditValue = _emp.Emp_Email;
                chkActived.CheckState = _emp.Emp_Actived == 1 ? CheckState.Checked : CheckState.Unchecked;


                txtDistrict.EditValue = _emp.Emp_District;
                txtCity.EditValue = _emp.Emp_City;

                txtCMND.EditValue = _emp.Emp_CMND;
                txtMaSoThue.EditValue = _emp.Emp_MaSoThue;
                txtBirthday.EditValue = _emp.Emp_Birthday;
                chkGender.Checked = _emp.Emp_Gender ?? false;
                txtNgayTuyen.EditValue = _emp.Emp_NgayTuyenDung;
                txtSucKhoe.EditValue = _emp.Emp_ThongTinSucKhoe;
                //newEmployee.Emp_Avatar = txtFullName.EditValue + string.Empty;
                try
                {
                    string urlImage = Path.Combine(_urlSave, _emp.Emp_Username.ToString(), _emp.Emp_Avatar);
                    FileStream fs = new FileStream(urlImage, FileMode.Open);
                    Image img = Image.FromStream(fs);
                    pictureEdit1.Image = img;
                    fs.Close();
                }
                catch
                {
                    pictureEdit1.Image = null;
                }

            }
        }

        bool Validation()
        {
            dxErrorProvider1.ClearErrors();

            if (txtFullName.EditValue == null || txtFullName.EditValue == "")
            {
                dxErrorProvider1.SetError(txtFullName, "Vui lòng nhập họ tên");
                return false;
            }
            return true;
        }

        employee addEmp()
        {
            employee newEmployee = new employee();
            newEmployee.Emp_FullName = txtFullName.EditValue + string.Empty;
            newEmployee.Emp_Phone = txtPhone.EditValue + string.Empty;
            newEmployee.Emp_Address = txtAddress.EditValue + string.Empty;
            newEmployee.Emp_District = txtDistrict.EditValue + string.Empty;
            newEmployee.Emp_City = txtCity.EditValue + string.Empty;
            newEmployee.Emp_Contact = txtContact.EditValue + string.Empty;
            newEmployee.Emp_Email = txtEmail.EditValue + string.Empty;
            newEmployee.Emp_CMND = txtCMND.EditValue + string.Empty;
            newEmployee.Emp_MaSoThue = txtMaSoThue.EditValue + string.Empty;
            newEmployee.Emp_Birthday = txtBirthday.DateTime;
            newEmployee.Emp_Gender = chkGender.Checked;
            newEmployee.Emp_NgayTuyenDung = txtNgayTuyen.DateTime;
            newEmployee.Emp_ThongTinSucKhoe = txtSucKhoe.EditValue + string.Empty;
            newEmployee.Emp_Actived = chkActived.CheckState == CheckState.Checked ? 1 : 0;

            return newEmployee;
        }

        string InitAvatarFileName(long empId)
        {
            MD5 md5Hash = MD5.Create();
            string hash = GetMd5Hash(md5Hash, empId.ToString() + DateTime.Now.Ticks);
            string fileExtension = Path.GetExtension(_fileImageUrl);
            return hash + fileExtension;
        }

        void copyImage()
        {
            string urlImageEmp = Path.Combine(_urlSave, _emp.Emp_Username.ToString());
            if (!Directory.Exists(urlImageEmp))
            {
                Directory.CreateDirectory(urlImageEmp);
            }
            if (!string.IsNullOrEmpty(_fileImageUrl))
            {
                string urlDest = Path.Combine(urlImageEmp, InitAvatarFileName(_emp.Emp_Username));
                try
                {
                    File.Delete(Path.Combine(_urlSave,_emp.Emp_Avatar));
                }
                catch
                {
                }
                try
                {
                    if (File.Exists(urlDest))
                    {
                        File.Delete(urlDest);
                    }
                    File.Copy(_fileImageUrl, urlDest);
                }
                catch
                {

                }

            }
        }

        string GetMd5Hash(MD5 md5Hash, string input)
        {

            // Convert the input string to a byte array and compute the hash. 
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

            // Create a new Stringbuilder to collect the bytes 
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data  
            // and format each one as a hexadecimal string. 
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string. 
            return sBuilder.ToString();
        }

        #endregion









    }
}